import json
import logging
import os

import config as c
import request as r


def get_countries() -> dict:
    countries_lst = dict()
    if os.path.exists(c.CITY_TMP_FILE):
        with open(c.CITY_TMP_FILE, 'r') as f:
            if f.readline() != "":
                for line in f.readlines():
                    countries_lst[f'{line.split("|")[0]}'] = line.split('|')[1][:-1]
                return countries_lst
    req = r.REQUEST()
    j = json.loads(req.get(f'{c.BASE_URL}{c.COUNTRIES_SUFFIX}?language={c.CURRENT_LANG}').text)
    with open(c.CITY_TMP_FILE, 'w+') as f:
        for i in j['countries']:
            t = f"{c.BASE_URL}/marketplace/api/redirect?url={c.BASE_URL}?language={c.CURRENT_LANG}&country={i['country']}"
            # t2 = req.get(t).url.split('?')[0]
            rsp = req.get(t)
            t2 = rsp.url.scheme + "://" + rsp.url.host
            # t2 = t2[:len(t2) - 2] + 'en' if '=' in t2 else t2
            countries_lst[i['localisedDisplayName']] = t2
            logging.info("获取：" + countries_lst[i['localisedDisplayName']])
            f.write(f"{i['localisedDisplayName']}|{countries_lst[i['localisedDisplayName']]}\n")
    return countries_lst

